package com.example.security;

import cn.hutool.json.JSONUtil;
import com.example.common.result.Result;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
//登录失败处理器
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        //设置返回类型和字符编码
        response.setContentType("application/json;charset=UTF-8");
        //定义一个response输出流
        ServletOutputStream outputStream = response.getOutputStream();

        //将异常消息封装成Result
        Result result;
        if (e instanceof DisabledException) {
            result = Result.error().message("账号被禁用");
        } else if (e instanceof LockedException) {
            result = Result.error().message("用户被锁定");
        } else if (e instanceof BadCredentialsException) {
            result = Result.error().message("账号或者密码错误");
        } else if (e instanceof InternalAuthenticationServiceException) {
            result = Result.error().message("未分配角色，请联系管理员！");
        } else {
            result = Result.error().message("未知错误！请联系管理员");
        }


        //将result写入输出流中
        outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
        //刷新此输出流并强制写出所有缓冲的输出字节
        outputStream.flush();
        //将输出流关闭
        outputStream.close();
    }
}
